<template>
  <div class="permissions-page">
    <div class="page-header">
      <h1>Permission Management</h1>
      <el-button type="primary" @click="showCreateDialog = true">
        <el-icon><Plus /></el-icon>
        Add Permission
      </el-button>
    </div>
    
    <el-card>
      <el-table v-loading="loading" :data="permissions" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="Name" />
        <el-table-column prop="description" label="Description" />
        <el-table-column prop="resource" label="Resource" />
        <el-table-column prop="action" label="Action" />
        <el-table-column label="Status" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isActive ? 'success' : 'danger'">
              {{ row.isActive ? 'Active' : 'Inactive' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="Actions" width="150">
          <template #default="{ row }">
            <el-button size="small" @click="editPermission(row)">
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button size="small" type="danger" @click="deletePermission(row)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- Create/Edit Permission Dialog -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingPermission ? 'Edit Permission' : 'Create Permission'"
      width="500px"
    >
      <el-form
        ref="permissionFormRef"
        :model="permissionForm"
        :rules="permissionRules"
        label-width="120px"
      >
        <el-form-item label="Name" prop="name">
          <el-input v-model="permissionForm.name" />
        </el-form-item>
        
        <el-form-item label="Description">
          <el-input v-model="permissionForm.description" type="textarea" />
        </el-form-item>
        
        <el-form-item label="Resource" prop="resource">
          <el-input v-model="permissionForm.resource" />
        </el-form-item>
        
        <el-form-item label="Action" prop="action">
          <el-select v-model="permissionForm.action" style="width: 100%">
            <el-option label="Create" value="Create" />
            <el-option label="Read" value="Read" />
            <el-option label="Update" value="Update" />
            <el-option label="Delete" value="Delete" />
          </el-select>
        </el-form-item>
        
        <el-form-item v-if="editingPermission" label="Status">
          <el-switch
            v-model="permissionForm.isActive"
            active-text="Active"
            inactive-text="Inactive"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="cancelEdit">Cancel</el-button>
        <el-button type="primary" :loading="saving" @click="savePermission">
          {{ editingPermission ? 'Update' : 'Create' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import api from '@/api'

interface Permission {
  id: number
  name: string
  description?: string
  resource: string
  action: string
  isActive: boolean
  createdAt: string
}

const permissions = ref<Permission[]>([])
const loading = ref(false)
const saving = ref(false)
const showCreateDialog = ref(false)
const editingPermission = ref<Permission | null>(null)
const permissionFormRef = ref<FormInstance>()

const permissionForm = reactive({
  name: '',
  description: '',
  resource: '',
  action: '',
  isActive: true
})

const permissionRules: FormRules = {
  name: [
    { required: true, message: 'Please input permission name', trigger: 'blur' }
  ],
  resource: [
    { required: true, message: 'Please input resource', trigger: 'blur' }
  ],
  action: [
    { required: true, message: 'Please select action', trigger: 'change' }
  ]
}

const loadPermissions = async () => {
  loading.value = true
  try {
    const response = await api.get('/permissions')
    permissions.value = response.data
  } catch (error) {
    ElMessage.error('Failed to load permissions')
  } finally {
    loading.value = false
  }
}

const editPermission = (permission: Permission) => {
  editingPermission.value = permission
  permissionForm.name = permission.name
  permissionForm.description = permission.description || ''
  permissionForm.resource = permission.resource
  permissionForm.action = permission.action
  permissionForm.isActive = permission.isActive
  showCreateDialog.value = true
}

const deletePermission = async (permission: Permission) => {
  try {
    await ElMessageBox.confirm(
      `Are you sure you want to delete permission "${permission.name}"?`,
      'Confirm Delete',
      {
        confirmButtonText: 'Delete',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }
    )
    
    await api.delete(`/permissions/${permission.id}`)
    ElMessage.success('Permission deleted successfully')
    loadPermissions()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('Failed to delete permission')
    }
  }
}

const savePermission = async () => {
  if (!permissionFormRef.value) return
  
  await permissionFormRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true
      try {
        if (editingPermission.value) {
          await api.put(`/permissions/${editingPermission.value.id}`, permissionForm)
          ElMessage.success('Permission updated successfully')
        } else {
          await api.post('/permissions', permissionForm)
          ElMessage.success('Permission created successfully')
        }
        
        showCreateDialog.value = false
        loadPermissions()
        resetForm()
      } catch (error) {
        ElMessage.error(editingPermission.value ? 'Failed to update permission' : 'Failed to create permission')
      } finally {
        saving.value = false
      }
    }
  })
}

const cancelEdit = () => {
  showCreateDialog.value = false
  resetForm()
}

const resetForm = () => {
  editingPermission.value = null
  Object.assign(permissionForm, {
    name: '',
    description: '',
    resource: '',
    action: '',
    isActive: true
  })
  permissionFormRef.value?.resetFields()
}

onMounted(() => {
  loadPermissions()
})
</script>

<style scoped>
.permissions-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}
</style>
